<template>
	<div class="home-container layout-pd">
		<el-row :gutter="15" class="home-card-one mb15">
			<el-col
				:xs="24"
				:sm="12"
				:md="12"
				:lg="6"
				:xl="6"
				v-for="(v, k) in state.homeOne"
				:key="k"
				:class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }"
			>
				<div class="home-card-item flex">
					<div class="flex-margin flex w100" :class="` home-one-animation${k}`">
						<div class="flex-auto">
							<span class="font30">{{ v.num1 }}</span>
							<span class="ml5 font16" :style="{ color: v.color1 }">+{{ v.num2 }}</span>
							<div class="mt10">{{ v.num3 }}</div>
						</div>
						<div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">
							<i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
    <el-row :gutter="15" class="home-card-one mb15">
      <el-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="6"
        :xl="6"
        v-for="(v, k) in state.homeTwo"
        :key="k"
        :class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }"
      >
        <div class="home-card-item flex">
          <div class="flex-margin flex w100" :class="` home-one-animation${k}`">
            <div class="flex-auto">
              <span class="font30">{{ v.num1 }}</span>
<!--              <span class="ml5 font16" :style="{ color: v.color1 }">{{ v.num2 }}</span>-->
              <div class="mt10">{{ v.num3 }}</div>
            </div>
            <div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">
              <i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-job mb15">
      <el-col>
        <el-card class="box-card" shadow="hover" body-style="padding-bottom:0px;">
          <template #header>
            <div class="card-header">
              {{t('message.home.timeSelect')}}：
              <el-date-picker
                v-model="state.jobDateSelect"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator="-"
                size="default"
                :start-placeholder="t('message.dateMsg.startDate')"
                :end-placeholder="t('message.dateMsg.endDate')"
                @change="initLineJobChart()"
              />
            </div>
          </template>
              <el-row :gutter="15" class="home-card-two mb15">
                <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
                  <div class="home-card-item">
                    <div style="height: 100%" ref="homeLineJobRef"></div>
                  </div>
                </el-col>
                <el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
                  <div class="home-card-item">
                    <div style="height: 100%" ref="homePieJobRef"></div>
                  </div>
                </el-col>
              </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="15" class="home-card-delay mb15">
      <el-col>
        <el-card class="box-card" shadow="hover" body-style="padding-bottom:0px;">
          <template #header>
            <div class="card-header">
              {{t('message.home.timeSelect')}}：
              <el-date-picker
                v-model="state.delayDateSelect"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator="-"
                size="default"
                :start-placeholder="t('message.dateMsg.startDate')"
                :end-placeholder="t('message.dateMsg.endDate')"
                @change="initLineDelayChart()"
              />
            </div>
          </template>
          <el-row :gutter="15" class="home-card-two mb15">
            <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
              <div class="home-card-item">
                <div style="height: 100%" ref="homeLineDelayRef"></div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
              <div class="home-card-item">
                <div style="height: 100%" ref="homePieDelayRef"></div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
	</div>
</template>

<script setup lang="ts" name="home">
import { reactive, onMounted, ref, watch, nextTick, onActivated, markRaw } from 'vue';
import * as echarts from 'echarts';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import {useHomeApi} from "/@/api/home";
import {Local} from "/@/utils/storage";
import {useI18n} from "vue-i18n";
import {getChartShortcuts} from "/@/utils/data";


// 定义变量内容
const {t} = useI18n();

const shortcuts = getChartShortcuts();

// 定义变量内容
const homeLineJobRef = ref();
const homePieJobRef = ref();
const homeLineDelayRef = ref();
const homePieDelayRef = ref();
const homeApi = useHomeApi();
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);

const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24)

const state = reactive({
  jobDateSelect: [
    start,
    end,
  ],
  delayDateSelect: [
    start,
    end,
  ],
	global: {
		homeChartOne: null,
		homeChartTwo: null,
		homeCharThree: null,
		homeCharFour: null,
		dispose: [null, '', undefined],
	} as any,
	homeOne: [
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    },
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    },
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    },
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    }
  ],
  homeTwo: [
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    },
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    },
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    },
    {
      num1: '',
      num2: '',
      num3: '',
      num4: '',
      color1: '',
      color2: '',
      color3: '',
    }
  ],
	myCharts: [] as EmptyArrayType,
	charts: {
		theme: '',
		bgColor: '',
		color: '#303133',
	},
});

// 折线图
const initLineJobChart = async () => {
  let request = {
    namespaceId: Local.get("nid") == null ? 1 : Local.get("nid"),
    beginTime: Date.parse(state.jobDateSelect[0].toString()) / 1000,
    endTime: Date.parse(state.jobDateSelect[1].toString()) / 1000,
  };
  // Font Awesome icon
  let data = await homeApi.getJobChart(request)

  let percentValues: number[] = [];
  let percentList = data['percentList'];
  for (const percentValue in percentList) {
    percentValues.push(Number(percentList[percentValue])/100);
  }

  if (!state.global.dispose.some((b: any) => b === state.global.homeChartOne)) state.global.homeChartOne.dispose();
  state.global.homeChartOne = markRaw(echarts.init(homeLineJobRef.value, state.charts.theme));
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: t('message.home.job.chartTitle'),
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    grid: {top: 70, right: 20, bottom: 30, left: 30},
    tooltip: {trigger: 'axis'},
    legend: {data: [t('message.home.status.success'), t('message.home.status.fail'), t('message.home.status.running')], right: 0},
    xAxis: {
      data: data['axisData'],
    },
    yAxis: [
      {
        type: 'value',
        name: t('message.home.taskNum'),
        splitLine: {show: true, lineStyle: {type: 'dashed', color: '#f5f5f5'}},
      },
    ],
    series: [
      {
        name: t('message.home.status.success'),
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: data['successData'],
        lineStyle: {color: '#91cc75'},
        itemStyle: {color: '#91cc75', borderColor: '#91cc75'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#91cc75'},
            {offset: 1, color: '#91cc75'},
          ]),
        },
      },
      {
        name: t('message.home.status.fail'),
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: data['failData'],
        lineStyle: {color: '#ee6666'},
        itemStyle: {color: '#ee6666', borderColor: '#ee6666'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#ee6666'},
            {offset: 1, color: '#ee6666'},
          ]),
        },
      },
      {
        name: t('message.home.status.running'),
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: data['runningData'],
        lineStyle: {color: '#73c0de'},
        itemStyle: {color: '#73c0de', borderColor: '#73c0de'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#73c0de'},
            {offset: 1, color: '#73c0de'},
          ]),
        },
      },
    ],
  };
  state.global.homeChartOne.setOption(option);
  state.myCharts.push(state.global.homeChartOne);

  setTimeout(() => {
    initPieJobChart(percentValues);
  }, 500);
};
// 饼图
const initPieJobChart = (percentValues : number[]) => {
	if (!state.global.dispose.some((b: any) => b === state.global.homeChartTwo)) state.global.homeChartTwo.dispose();
	state.global.homeChartTwo = markRaw(echarts.init(homePieJobRef.value, state.charts.theme));
  var getname = [
    t('message.home.status.waiting'),
    t('message.home.status.running'),
    t('message.home.status.success'),
    t('message.home.status.fail'),
    t('message.home.status.stop'),
  ];
  var getvalue = percentValues;
	var data = [];
	for (var i = 0; i < getname.length; i++) {
		data.push({ name: getname[i], value: getvalue[i] });
	}
	const colorList = ['#9a60b4', '#73c0de', '#91cc75', '#ee6666', '#ea7ccc'];
	const option = {
		backgroundColor: state.charts.bgColor,
		title: {
			text: t('message.home.job.percentTitle'),
			x: 'left',
			textStyle: { fontSize: '15', color: state.charts.color },
		},
		tooltip: { trigger: 'item', formatter: '{b} <br/> {c}%' },
		graphic: {
			elements: [
				{
					type: 'image',
					z: -1,
					style: {
						image: themeConfig.value.isIsDark
							? ''
							: '',
						width: 230,
						height: 230,
					},
					left: '16.5%',
					top: 'center',
				},
			],
		},
		legend: {
			type: 'scroll',
			orient: 'vertical',
			right: '0%',
			left: '65%',
			top: 'center',
			itemWidth: 14,
			itemHeight: 14,
			data: getname,
			textStyle: {
				rich: {
					name: {
						fontSize: 14,
						fontWeight: 400,
						width: 200,
						height: 35,
						padding: [0, 0, 0, 60],
						color: state.charts.color,
					},
					rate: {
						fontSize: 15,
						fontWeight: 500,
						height: 35,
						width: 40,
						padding: [0, 0, 0, 30],
						color: state.charts.color,
					},
				},
			},
		},
		series: [
			{
				type: 'pie',
				radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
				center: ['32%', '50%'],
				itemStyle: {
					color: function (params: any) {
						return colorList[params.dataIndex];
					},
				},
				label: { show: false },
				labelLine: { show: false },
				data: data,
			},
		],
	};
	state.global.homeChartTwo.setOption(option);
	state.myCharts.push(state.global.homeChartTwo);
};

const initLineDelayChart = async () => {

  let request = {
    namespaceId: Local.get("nid") == null ? 1 : Local.get("nid"),
    beginTime: Date.parse(state.jobDateSelect[0].toString()) / 1000,
    endTime: Date.parse(state.jobDateSelect[1].toString()) / 1000,
  };
  // Font Awesome icon
  let data = await homeApi.getDelayChart(request)
  let percentValues: number[] = [];
  let percentList = data['percentList'];
  for (const percentValue in percentList) {
    percentValues.push(Number(percentList[percentValue])/100);
  }

  if (!state.global.dispose.some((b: any) => b === state.global.homeCharThree)) state.global.homeCharThree.dispose();
  state.global.homeCharThree = markRaw(echarts.init(homeLineDelayRef.value, state.charts.theme));
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: t('message.home.delay.chartTitle'),
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    grid: {top: 70, right: 20, bottom: 30, left: 30},
    tooltip: {trigger: 'axis'},
    legend: {data: [t('message.home.status.success'), t('message.home.status.fail'), t('message.home.status.running')], right: 0},
    xAxis: {
      data: data['axisData'],
    },
    yAxis: [
      {
        type: 'value',
        name: t('message.home.taskNum'),
        splitLine: {show: true, lineStyle: {type: 'dashed', color: '#f5f5f5'}},
      },
    ],
    series: [
      {
        name: t('message.home.status.success'),
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: data['successData'],
        lineStyle: {color: '#91cc75'},
        itemStyle: {color: '#91cc75', borderColor: '#91cc75'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#91cc75'},
            {offset: 1, color: '#91cc75'},
          ]),
        },
      },
      {
        name: t('message.home.status.fail'),
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: data['failData'],
        lineStyle: {color: '#ee6666'},
        itemStyle: {color: '#ee6666', borderColor: '#ee6666'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#ee6666'},
            {offset: 1, color: '#ee6666'},
          ]),
        }
      },
      {
        name: t('message.home.status.running'),
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: data['runningData'],
        lineStyle: {color: '#73c0de'},
        itemStyle: {color: '#73c0de', borderColor: '#73c0de'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#73c0de'},
            {offset: 1, color: '#73c0de'},
          ]),
        },
      },
    ],
  };
  state.global.homeCharThree.setOption(option);
  state.myCharts.push(state.global.homeCharThree);

  setTimeout(() => {
    initPieDelayChart(percentValues);
  }, 500);
};

// 饼图
const initPieDelayChart = (percentValues : number[]) => {
  if (!state.global.dispose.some((b: any) => b === state.global.homeCharFour)) state.global.homeCharFour.dispose();
  state.global.homeCharFour = markRaw(echarts.init(homePieDelayRef.value, state.charts.theme));
  var getname = [
    t('message.home.status.waiting'),
    t('message.home.status.running'),
    t('message.home.status.success'),
    t('message.home.status.fail'),
    t('message.home.status.stop'),
  ];
  var getvalue = percentValues;
  var data = [];
  for (var i = 0; i < getname.length; i++) {
    data.push({ name: getname[i], value: getvalue[i] });
  }
  const colorList = ['#9a60b4', '#73c0de', '#91cc75', '#ee6666', '#ea7ccc'];
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: t('message.home.delay.percentTitle'),
      x: 'left',
      textStyle: { fontSize: '15', color: state.charts.color },
    },
    tooltip: { trigger: 'item', formatter: '{b} <br/> {c}%' },
    graphic: {
      elements: [
        {
          type: 'image',
          z: -1,
          style: {
            image: themeConfig.value.isIsDark
              ? ''
              : '',
            width: 230,
            height: 230,
          },
          left: '16.5%',
          top: 'center',
        },
      ],
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: '0%',
      left: '65%',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: getname,
      textStyle: {
        rich: {
          name: {
            fontSize: 14,
            fontWeight: 400,
            width: 200,
            height: 35,
            padding: [0, 0, 0, 60],
            color: state.charts.color,
          },
          rate: {
            fontSize: 15,
            fontWeight: 500,
            height: 35,
            width: 40,
            padding: [0, 0, 0, 30],
            color: state.charts.color,
          },
        },
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
        center: ['32%', '50%'],
        itemStyle: {
          color: function (params: any) {
            return colorList[params.dataIndex];
          },
        },
        label: { show: false },
        labelLine: { show: false },
        data: data,
      },
    ],
  };
  state.global.homeCharFour.setOption(option);
  state.myCharts.push(state.global.homeCharFour);
};
// 批量设置 echarts resize
const initEchartsResizeFun = () => {
	nextTick(() => {
		for (let i = 0; i < state.myCharts.length; i++) {
			setTimeout(() => {
				state.myCharts[i].resize();
			}, i * 1000);
		}
	});
};
// 批量设置 echarts resize
const initEchartsResize = () => {
	window.addEventListener('resize', initEchartsResizeFun);
};

const getTaskData = async () => {
  let request = {
    namespaceId: Local.get("nid") == null ? 1 : Local.get("nid"),
  };
  // Font Awesome icon
  let data = await homeApi.getTaskData(request)
  state.homeOne[0] = {
    num1: data['job']['total'],
    num2: data['job']['newTotal'],
    num3: t('message.home.countOne.one'),
    num4: 'fa fa-history',
    color1: '#FF6462',
    color2: '--next-color-primary-lighter',
    color3: '--el-color-primary',
  }

  state.homeOne[1] = {
    num1: data['jobInstance']['total'],
    num2: data['jobInstance']['newTotal'],
    num3: t('message.home.countOne.two'),
    num4: 'fa fa-file',
    color1: '#6690F9',
    color2: '--next-color-success-lighter',
    color3: '--el-color-success',
  }

  state.homeOne[2] = {
    num1: data['job']['total'],
    num2: data['job']['newTotal'],
    num3: t('message.home.countOne.three'),
    num4: 'fa fa-tasks',
    color1: '#6690F9',
    color2: '--next-color-warning-lighter',
    color3: '--el-color-warning',
  }

  state.homeOne[3] = {
    num1: data['delayInstance']['total'],
    num2: data['delayInstance']['newTotal'],
    num3: t('message.home.countOne.four'),
    num4: 'fa fa-clipboard',
    color1: '#FF6462',
    color2: '--next-color-danger-lighter',
    color3: '--el-color-danger',
  }
}

const getSystemData = async () => {
  let request = {
    namespaceId: Local.get("nid") == null ? 1 : Local.get("nid"),
  };
  // Font Awesome icon
  let data = await homeApi.getSystemData(request)
  state.homeTwo[0] = {
    num1: data['app']['total'],
    num2: data['app']['newTotal'],
    num3: t('message.home.countTwo.one'),
    num4: 'fa fa-clone',
    color1: '#FF6462',
    color2: '--next-color-primary-lighter',
    color3: '--el-color-primary',
  };

  state.homeTwo[1] = {
    num1: data['server']['total'],
    num2: data['server']['newTotal'],
    num3: t('message.home.countTwo.two'),
    num4: 'fa fa-server',
    color1: '#6690F9',
    color2: '--next-color-success-lighter',
    color3: '--el-color-success',
  };

  state.homeTwo[2] = {
    num1: data['worker']['total'],
    num2: data['worker']['newTotal'],
    num3: t('message.home.countTwo.three'),
    num4: 'fa fa-desktop',
    color1: '#6690F9',
    color2: '--next-color-warning-lighter',
    color3: '--el-color-warning',
  };

  state.homeTwo[3] = {
    num1: data['slot']['total'],
    num2: data['slot']['newTotal'],
    num3: t('message.home.countTwo.four'),
    num4: 'fa fa-copy',
    color1: '#FF6462',
    color2: '--next-color-danger-lighter',
    color3: '--el-color-danger',
  };
}

// 页面加载时
onMounted(async () => {
  initEchartsResize();

  // Task data
  await getTaskData()

  // System data
  setTimeout(async () => {
    await getSystemData();
  }, 800)
});
// 由于页面缓存原因，keep-alive
onActivated(() => {
	initEchartsResizeFun();
});
// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
	() => isTagsViewCurrenFull.value,
	() => {
		initEchartsResizeFun();
	}
);
// 监听 pinia 中是否开启深色主题
watch(
	() => themeConfig.value.isIsDark,
	(isIsDark) => {
		nextTick(() => {
			state.charts.theme = isIsDark ? 'dark' : '';
			state.charts.bgColor = isIsDark ? 'transparent' : '';
			state.charts.color = isIsDark ? '#dadada' : '#303133';
			setTimeout(async () => {
        await initLineJobChart();
      }, 500);
			setTimeout(async () => {
        await initLineDelayChart();
      }, 700);
		});
	},
	{
		deep: true,
		immediate: true,
	}
);
</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
	overflow: hidden;
	.home-card-one,
	.home-card-two,
	.home-card-three {
		.home-card-item {
			width: 100%;
			height: 130px;
			border-radius: 4px;
			transition: all ease 0.3s;
			padding: 20px;
			overflow: hidden;
			background: var(--el-color-white);
			color: var(--el-text-color-primary);
			border: 1px solid var(--next-border-color-light);
			&:hover {
				box-shadow: 0 2px 12px var(--next-color-dark-hover);
				transition: all ease 0.3s;
			}
			&-icon {
				width: 70px;
				height: 70px;
				border-radius: 100%;
				flex-shrink: 1;
				i {
					color: var(--el-text-color-placeholder);
				}
			}
			&-title {
				font-size: 15px;
				font-weight: bold;
				height: 30px;
			}
		}
	}
	.home-card-one {
		@for $i from 0 through 3 {
			.home-one-animation#{$i} {
				opacity: 0;
				animation-name: error-num;
				animation-duration: 0.5s;
				animation-fill-mode: forwards;
				animation-delay: calc($i/4) + s;
			}
		}
	}
	.home-card-two,
	.home-card-three {
		.home-card-item {
			height: 400px;
			width: 100%;
			overflow: hidden;
			.home-monitor {
				height: 100%;
				.flex-warp-item {
					width: 25%;
					height: 111px;
					display: flex;
					.flex-warp-item-box {
						margin: auto;
						text-align: center;
						color: var(--el-text-color-primary);
						display: flex;
						border-radius: 5px;
						background: var(--next-bg-color);
						cursor: pointer;
						transition: all 0.3s ease;
						&:hover {
							background: var(--el-color-primary-light-9);
							transition: all 0.3s ease;
						}
					}
					@for $i from 0 through $homeNavLengh {
						.home-animation#{$i} {
							opacity: 0;
							animation-name: error-num;
							animation-duration: 0.5s;
							animation-fill-mode: forwards;
							animation-delay: calc($i/10) + s;
						}
					}
				}
			}
		}
	}

  .home-card-delay{
    margin-top: 16px;
  }
}
</style>
